<template>
  <div class="admin-container">
    <!-- 页面标题与操作区 -->
    <div class="page-header">
      <h2>工人-池塘管理</h2>
      <div class="operation-btns">
        <button class="btn primary" @click="openAddDialog">新增基准值</button>
        <button
          class="btn danger"
          @click="batchDeletePonds"
          :disabled="selectedNames.length === 0"
        >
          批量删除
        </button>
      </div>
    </div>

    <!-- 搜索区 -->
    <div class="search-bar">
      <input
        type="text"
        v-model="searchName"
        placeholder="输入池塘名称搜索"
        class="search-input"
      />
      <button class="btn primary" @click="fetchPondList">搜索</button>
      <button class="btn default" @click="resetSearch">重置</button>
    </div>

    <!-- 池塘基准值列表 -->
    <div class="table-container">
      <table class="data-table">
        <thead>
          <tr>
            <th class="select-col">
              <input
                type="checkbox"
                @change="selectAll"
                v-model="allSelected"
              />
            </th>
            <th>池塘名称</th>
            <th>最低温度(℃)</th>
            <th>最高温度(℃)</th>
            <th>最低水位(m)</th>
            <th>最高水位(m)</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="pond in pondList" :key="pond.name">
            <td>
              <input
                type="checkbox"
                v-model="selectedNames"
                :value="pond.name"
                @change="checkAllSelected"
              />
            </td>
            <td>{{ pond.name }}</td>
            <td>{{ pond.minTemp || "-" }}</td>
            <td>{{ pond.maxTemp || "-" }}</td>
            <td>{{ pond.minLevel || "-" }}</td>
            <td>{{ pond.maxLevel || "-" }}</td>
            <td class="operation-col">
              <button class="btn text" @click="openEditDialog(pond)">
                编辑
              </button>
              <button class="btn text danger" @click="deletePond(pond.name)">
                删除
              </button>
            </td>
          </tr>
          <tr v-if="pondList.length === 0">
            <td colspan="7" class="empty-state">暂无数据</td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 新增池塘基准值弹窗 -->
    <div class="modal-mask" v-if="addDialogVisible">
      <div class="modal">
        <div class="modal-header">
          <h3>新增池塘基准值</h3>
          <button class="close-btn" @click="addDialogVisible = false">
            &times;
          </button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="submitAddForm" class="modal-form">
            <div class="form-group">
              <label>池塘名称 <span class="required">*</span></label>
              <input
                type="text"
                v-model="addForm.name"
                @input="validateName(addForm.name, 'add')"
                @blur="validateName(addForm.name, 'add')"
              />
              <p v-if="addErrors.name" class="error-message">
                {{ addErrors.name }}
              </p>
            </div>
            <div class="form-group">
              <label>最低温度(℃) <span class="required">*</span></label>
              <input
                type="number"
                step="0.1"
                v-model="addForm.minTemp"
                @input="validateNumber(addForm.minTemp, 'minTemp', 'add')"
                @blur="validateNumber(addForm.minTemp, 'minTemp', 'add')"
              />
              <p v-if="addErrors.minTemp" class="error-message">
                {{ addErrors.minTemp }}
              </p>
            </div>
            <div class="form-group">
              <label>最高温度(℃) <span class="required">*</span></label>
              <input
                type="number"
                step="0.1"
                v-model="addForm.maxTemp"
                @input="validateTempRange('add')"
                @blur="validateTempRange('add')"
              />
              <p v-if="addErrors.maxTemp" class="error-message">
                {{ addErrors.maxTemp }}
              </p>
            </div>
            <div class="form-group">
              <label>最低水位(m) <span class="required">*</span></label>
              <input
                type="number"
                step="0.1"
                v-model="addForm.minLevel"
                @input="validateNumber(addForm.minLevel, 'minLevel', 'add')"
                @blur="validateNumber(addForm.minLevel, 'minLevel', 'add')"
              />
              <p v-if="addErrors.minLevel" class="error-message">
                {{ addErrors.minLevel }}
              </p>
            </div>
            <div class="form-group">
              <label>最高水位(m) <span class="required">*</span></label>
              <input
                type="number"
                step="0.1"
                v-model="addForm.maxLevel"
                @input="validateLevelRange('add')"
                @blur="validateLevelRange('add')"
              />
              <p v-if="addErrors.maxLevel" class="error-message">
                {{ addErrors.maxLevel }}
              </p>
            </div>
            <div class="form-actions">
              <button
                type="button"
                class="btn default"
                @click="addDialogVisible = false"
              >
                取消
              </button>
              <button
                type="submit"
                class="btn primary"
                :disabled="!isAddFormValid"
              >
                确定
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- 编辑池塘基准值弹窗 -->
    <div class="modal-mask" v-if="editDialogVisible">
      <div class="modal">
        <div class="modal-header">
          <h3>编辑池塘基准值</h3>
          <button class="close-btn" @click="editDialogVisible = false">
            &times;
          </button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="submitEditForm" class="modal-form">
            <div class="form-group">
              <label>池塘名称 <span class="required">*</span></label>
              <input
                type="text"
                v-model="editForm.name"
                @input="validateName(editForm.name, 'edit')"
                @blur="validateName(editForm.name, 'edit')"
                :readonly="true"
              />
              <p v-if="editErrors.name" class="error-message">
                {{ editErrors.name }}
              </p>
            </div>
            <div class="form-group">
              <label>最低温度(℃)</label>
              <input
                type="number"
                step="0.1"
                v-model="editForm.minTemp"
                @input="validateNumber(editForm.minTemp, 'minTemp', 'edit')"
                @blur="validateNumber(editForm.minTemp, 'minTemp', 'edit')"
              />
              <p v-if="editErrors.minTemp" class="error-message">
                {{ editErrors.minTemp }}
              </p>
            </div>
            <div class="form-group">
              <label>最高温度(℃)</label>
              <input
                type="number"
                step="0.1"
                v-model="editForm.maxTemp"
                @input="validateTempRange('edit')"
                @blur="validateTempRange('edit')"
              />
              <p v-if="editErrors.maxTemp" class="error-message">
                {{ editErrors.maxTemp }}
              </p>
            </div>
            <div class="form-group">
              <label>最低水位(m)</label>
              <input
                type="number"
                step="0.1"
                v-model="editForm.minLevel"
                @input="validateNumber(editForm.minLevel, 'minLevel', 'edit')"
                @blur="validateNumber(editForm.minLevel, 'minLevel', 'edit')"
              />
              <p v-if="editErrors.minLevel" class="error-message">
                {{ editErrors.minLevel }}
              </p>
            </div>
            <div class="form-group">
              <label>最高水位(m)</label>
              <input
                type="number"
                step="0.1"
                v-model="editForm.maxLevel"
                @input="validateLevelRange('edit')"
                @blur="validateLevelRange('edit')"
              />
              <p v-if="editErrors.maxLevel" class="error-message">
                {{ editErrors.maxLevel }}
              </p>
            </div>
            <div class="form-actions">
              <button
                type="button"
                class="btn default"
                @click="editDialogVisible = false"
              >
                取消
              </button>
              <button
                type="submit"
                class="btn primary"
                :disabled="!isEditFormValid"
              >
                确定
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- 提示消息 -->
    <div class="toast" v-if="toastMessage">{{ toastMessage }}</div>
  </div>
</template>
<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import axios from "axios";
import { inMemoryStorage } from "/src/router/index.js";
import { useRouter } from "vue-router";

// 初始化路由实例
const router = useRouter();

// axios 核心配置
axios.defaults.baseURL = "http://localhost:8080";
axios.defaults.withCredentials = true;
axios.defaults.headers.common["Accept"] = "application/json";
axios.defaults.headers.post["Content-Type"] = "application/json;charset=UTF-8";

// 请求拦截器
axios.interceptors.request.use(
  (config) => {
    const token = inMemoryStorage.token || "";
    if (token) {
      config.headers["Authorization"] = `Bearer ${token}`;
    }
    if (!token && !config.url.includes("/login")) {
      router.replace("/");
      showToast("请先登录");
      return Promise.reject(new Error("未登录"));
    }
    return config;
  },
  (error) => Promise.reject(error)
);

// 响应拦截器
axios.interceptors.response.use(
  (response) => {
    if (response.data?.message) {
      showToast(response.data.message);
    } else if (typeof response.data === "string") {
      showToast(response.data);
    }
    return response;
  },
  (error) => {
    if (error.response) {
      const status = error.response.status;
      const message = error.response.data?.message || "操作失败";
      showToast(`[${status}] ${message}`);
      if (status === 401) {
        inMemoryStorage.token = null;
        router.replace("/");
        showToast("登录已失效，请重新登录");
      }
    } else if (error.request) {
      showToast("无法连接服务器，请检查后端是否启动");
    } else {
      showToast("请求异常：" + error.message);
    }
    return Promise.reject(error);
  }
);

// 数据列表
const allPonds = ref([]);
const pondList = ref([]);
// 搜索参数
const searchName = ref("");

// 选择相关
const selectedNames = ref([]);
const allSelected = ref(false);

// 弹窗控制
const addDialogVisible = ref(false);
const editDialogVisible = ref(false);

// 表单数据
const addForm = reactive({
  name: "",
  minTemp: "",
  maxTemp: "",
  minLevel: "",
  maxLevel: "",
});

const editForm = reactive({
  name: "",
  minTemp: "",
  maxTemp: "",
  minLevel: "",
  maxLevel: "",
});

// 错误信息
const addErrors = reactive({
  name: "",
  minTemp: "",
  maxTemp: "",
  minLevel: "",
  maxLevel: "",
});

const editErrors = reactive({
  name: "",
  minTemp: "",
  maxTemp: "",
  minLevel: "",
  maxLevel: "",
});

const toastMessage = ref("");

// 表单验证状态
const isAddFormValid = computed(() => {
  return (
    !addErrors.name &&
    !addErrors.minTemp &&
    !addErrors.maxTemp &&
    !addErrors.minLevel &&
    !addErrors.maxLevel &&
    addForm.name.trim() &&
    addForm.minTemp !== "" &&
    addForm.maxTemp !== "" &&
    addForm.minLevel !== "" &&
    addForm.maxLevel !== ""
  );
});

const isEditFormValid = computed(() => {
  return (
    !editErrors.name &&
    !editErrors.minTemp &&
    !editErrors.maxTemp &&
    !editErrors.minLevel &&
    !editErrors.maxLevel &&
    editForm.name.trim()
  );
});

// 加载池塘基准值列表
const fetchAllPonds = async () => {
  try {
    const response = await axios.post("/device/operate/selectPondReference");
    allPonds.value = response.data || [];
    filterPondsByName(); // 触发过滤
  } catch (error) {
    console.error("获取池塘基准值列表失败:", error);
    showToast("获取数据失败，请重试");
  }
};

// 前端按池塘名称过滤
const filterPondsByName = () => {
  const nameStr = searchName.value.trim();
  if (!nameStr) {
    pondList.value = [...allPonds.value];
    return;
  }

  // 模糊搜索池塘名称
  const filtered = allPonds.value.filter((pond) => pond.name.includes(nameStr));
  pondList.value = filtered;
};

// 搜索触发
const fetchPondList = async () => {
  await fetchAllPonds();
};

// 页面加载时初始化
onMounted(() => {
  fetchPondList();
});

// 提示消息
const showToast = (message) => {
  toastMessage.value = message;
  setTimeout(() => {
    toastMessage.value = "";
  }, 3000);
};

// 全选/取消全选
const selectAll = () => {
  if (allSelected.value) {
    selectedNames.value = pondList.value.map((pond) => pond.name);
  } else {
    selectedNames.value = [];
  }
};

// 检查全选状态
const checkAllSelected = () => {
  allSelected.value =
    pondList.value.length > 0 &&
    selectedNames.value.length === pondList.value.length;
};

// 重置搜索
const resetSearch = () => {
  searchName.value = "";
  fetchPondList();
};

// 验证池塘名称
const validateName = (value, type) => {
  const errors = type === "add" ? addErrors : editErrors;
  const nameStr = value.trim();
  if (!nameStr) {
    errors.name = "池塘名称不能为空";
  } else if (nameStr.length > 50) {
    errors.name = "池塘名称长度不能超过50个字符";
  } else {
    // 新增时检查名称是否重复
    if (
      type === "add" &&
      allPonds.value.some((pond) => pond.name === nameStr)
    ) {
      errors.name = "该池塘名称已存在";
    } else {
      errors.name = "";
    }
  }
};

// 验证数字输入
const validateNumber = (value, key, type) => {
  const errors = type === "add" ? addErrors : editErrors;
  if (value === "" && type === "edit") {
    errors[key] = ""; // 编辑时可为空（使用默认值）
    return;
  }
  if (value === "" && type === "add") {
    errors[key] = `${key.includes("Temp") ? "温度" : "水位"}不能为空`;
    return;
  }
  const num = Number(value);
  if (isNaN(num) || num < 0) {
    errors[key] = `${key.includes("Temp") ? "温度" : "水位"}必须为非负数字`;
  } else {
    errors[key] = "";
  }
};

// 验证温度范围（最高温度>最低温度）
const validateTempRange = (type) => {
  const form = type === "add" ? addForm : editForm;
  const errors = type === "add" ? addErrors : editErrors;

  if (form.minTemp === "" || form.maxTemp === "") return;

  const min = Number(form.minTemp);
  const max = Number(form.maxTemp);

  if (!isNaN(min) && !isNaN(max) && max <= min) {
    errors.maxTemp = "最高温度必须大于最低温度";
  } else {
    errors.maxTemp = "";
  }
};

// 验证水位范围（最高水位>最低水位）
const validateLevelRange = (type) => {
  const form = type === "add" ? addForm : editForm;
  const errors = type === "add" ? addErrors : editErrors;

  if (form.minLevel === "" || form.maxLevel === "") return;

  const min = Number(form.minLevel);
  const max = Number(form.maxLevel);

  if (!isNaN(min) && !isNaN(max) && max <= min) {
    errors.maxLevel = "最高水位必须大于最低水位";
  } else {
    errors.maxLevel = "";
  }
};

// 打开新增弹窗
const openAddDialog = () => {
  addForm.name = "";
  addForm.minTemp = "";
  addForm.maxTemp = "";
  addForm.minLevel = "";
  addForm.maxLevel = "";
  Object.keys(addErrors).forEach((key) => (addErrors[key] = ""));
  addDialogVisible.value = true;
};

// 提交新增表单
const submitAddForm = async () => {
  try {
    const payload = {
      name: addForm.name.trim(),
      minTemp: Number(addForm.minTemp),
      maxTemp: Number(addForm.maxTemp),
      minLevel: Number(addForm.minLevel),
      maxLevel: Number(addForm.maxLevel),
    };
    await axios.post("/device/operate/addPondReference", payload);
    addDialogVisible.value = false;
    await fetchPondList();
  } catch (error) {
    console.error("新增失败:", error);
    showToast("新增失败，请重试");
  }
};

// 打开编辑弹窗
const openEditDialog = (pond) => {
  editForm.name = pond.name;
  editForm.minTemp = pond.minTemp || "";
  editForm.maxTemp = pond.maxTemp || "";
  editForm.minLevel = pond.minLevel || "";
  editForm.maxLevel = pond.maxLevel || "";
  Object.keys(editErrors).forEach((key) => (editErrors[key] = ""));
  editDialogVisible.value = true;
};

// 提交编辑表单
const submitEditForm = async () => {
  try {
    const updateData = {
      name: editForm.name.trim(),
      // 只传递有值的字段（后端支持部分更新）
      ...(editForm.minTemp !== "" && { minTemp: Number(editForm.minTemp) }),
      ...(editForm.maxTemp !== "" && { maxTemp: Number(editForm.maxTemp) }),
      ...(editForm.minLevel !== "" && { minLevel: Number(editForm.minLevel) }),
      ...(editForm.maxLevel !== "" && { maxLevel: Number(editForm.maxLevel) }),
    };
    await axios.post("/device/operate/updatePondReference", updateData);
    editDialogVisible.value = false;
    await fetchPondList();
  } catch (error) {
    console.error("编辑失败:", error);
    showToast("编辑失败，请重试");
  }
};

// 单个删除
const deletePond = async (name) => {
  if (!confirm(`确定要删除 ${name} 的基准值吗？`)) return;

  try {
    await axios.post(
      "/device/operate/deletePondReference",
      {},
      {
        params: { name },
      }
    );
    await fetchPondList();
    selectedNames.value = selectedNames.value.filter((n) => n !== name);
    checkAllSelected();
  } catch (error) {
    console.error("删除失败:", error);
    showToast("删除失败，请重试");
  }
};

// 批量删除
const batchDeletePonds = async () => {
  if (!confirm(`确定要删除选中的 ${selectedNames.value.length} 条基准值吗？`))
    return;

  try {
    // 循环删除（根据后端接口设计，若支持批量删除可优化）
    for (const name of selectedNames.value) {
      await axios.post(
        "/device/operate/deletePondReference",
        {},
        {
          params: { name },
        }
      );
    }
    showToast("批量删除成功");
    selectedNames.value = [];
    allSelected.value = false;
    await fetchPondList();
  } catch (error) {
    console.error("批量删除失败:", error);
    showToast("批量删除失败，请重试");
  }
};
</script>
<style scoped>
.admin-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.operation-btns {
  display: flex;
  gap: 10px;
}

.search-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  align-items: center;
}

.search-input {
  flex: 0 0 300px;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.table-container {
  overflow-x: auto;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  border: 1px solid #eee;
}

.data-table th,
.data-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.data-table th {
  background-color: #f9f9f9;
  font-weight: 600;
}

.select-col {
  width: 50px;
}

.operation-col {
  display: flex;
  gap: 10px;
}

.empty-state {
  text-align: center;
  padding: 40px;
  color: #999;
}

.modal-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal {
  background-color: white;
  border-radius: 6px;
  width: 100%;
  max-width: 500px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.modal-header {
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-body {
  padding: 20px;
}

.modal-form {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.form-group label {
  font-weight: 500;
  color: #333;
}

.form-group input,
.form-group textarea {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.form-group textarea {
  resize: vertical;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 10px;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #999;
}

.close-btn:hover {
  color: #333;
}

.error-message {
  color: #f5222d;
  font-size: 12px;
  margin: 0;
}

.toast {
  position: fixed;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 10px 20px;
  border-radius: 4px;
  z-index: 1001;
  animation: fadein 0.3s, fadeout 0.3s 2.7s;
}

.required {
  color: #f5222d;
}

/* 按钮样式 */
.btn {
  padding: 8px 16px;
  border-radius: 4px;
  border: none;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn.primary {
  background-color: #409eff;
  color: white;
}

.btn.primary:hover:not(:disabled) {
  background-color: #66b1ff;
}

.btn.danger {
  background-color: #f5222d;
  color: white;
}

.btn.danger:hover:not(:disabled) {
  background-color: #ff4d4f;
}

.btn.warning {
  background-color: #faad14;
  color: white;
}

.btn.warning:hover:not(:disabled) {
  background-color: #ffc53d;
}

.btn.default {
  background-color: #f5f5f5;
  color: #333;
}

.btn.default:hover:not(:disabled) {
  background-color: #e8e8e8;
}

.btn.text {
  background: none;
  color: #666;
  padding: 4px 8px;
}

.btn.text:hover {
  color: #409eff;
}

.btn.text.primary {
  color: #409eff;
}

.btn.text.danger {
  color: #f5222d;
}

.btn.text.success {
  color: #52c41a;
}

/* 动画效果 */
@keyframes fadein {
  from {
    top: 0;
    opacity: 0;
  }
  to {
    top: 20px;
    opacity: 1;
  }
}

@keyframes fadeout {
  from {
    top: 20px;
    opacity: 1;
  }
  to {
    top: 0;
    opacity: 0;
  }
}

/* 适配小屏幕 */
@media (max-width: 768px) {
  .admin-container {
    padding: 10px;
  }

  .search-input {
    flex: 1;
  }

  .operation-col {
    flex-direction: column;
    gap: 5px;
  }

  .modal {
    width: 90%;
  }
}
</style>
